import React from 'react';
import {Spin, Card, Button, Table, Row, Col} from 'antd';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import PropTypes from 'prop-types';
import {transportType, declarePlace, declareType, currency} from '../Enum';
import routes from './routes';
import {TABLE, DATE_FORMAT} from '../constants';
import {conventEnumValueToString, formatAmount, formatDateTime, formatPercent} from '../utils';
import {getDetail, abandonData} from './api';
import {injectIntl} from './intl';
import {PERMISSION} from './constants';
import {hasPermissions, generateRowSpanData} from './utils';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import styles from './style.css';
const {Description} = DescriptionList;
class DetailPanel extends React.PureComponent {
    state = {
        isFetching: false,
        data: {},
        details: [],
        shipmentDetails: []
    }
    componentDidMount() {
        this.getDetailInfo();
    }
    getDetailInfo = () => {
        const id = this.props.id;
        this.setState({isFetching: true});
        getDetail(id)
            .then(res => {
                if(res.ok)
                    this.setState({
                        isFetching: false,
                        data: res.data,
                        details: res.data.details,
                        shipmentDetails: res.data.shipmentDetails
                    });
                else
                    this.setState(({
                        isFetching: false
                    }));
            });
    }
    onCancel = () => {
        this.props.history.push(routes.query.url());
    }
    onClickAbandon = () => {
        this.setState({loading: true});
        const data = {
            rowVersion: this.state.data.rowVersion
        };
        abandonData(this.state.data.id, data)
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.successReturn();
            });
    }
    render() {
        const {data, details, shipmentDetails} = this.state;
        const {formatMessage} = this.props.intl;
        const operations = [];
        if(hasPermissions(this.props.permissions, PERMISSION.update) && hasPermissions(data.options, PERMISSION.update))
            operations.push(<Button key="update" href={`#${routes.update.format(this.props.id)}`} size="small">{
                formatMessage({
                    id: 'detailPanel.update',
                    defaultMessage: '编辑'
                })
            }</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.abandon) && hasPermissions(data.options, PERMISSION.abandon))
            operations.push(<WrappedPopconfirm
                key="abandon"
                id={this.props.id}
                placement="topLeft"
                onConfirm={this.onClickAbandon}
                title={formatMessage({
                    id: 'detailPanel.validate.abandon',
                    defaultMessage: '是否确认作废？'
                })}>
                <Button key="abandon" size="small">{
                    formatMessage({
                        id: 'detailPanel.abandon',
                        defaultMessage: '作废'
                    })
                }</Button>
            </WrappedPopconfirm>);
        const newDetails = generateRowSpanData(details, 'packingListCode', ['packingListCode', 'partSaleOrderCode']);
        const colums = [{
            title: formatMessage({
                id: 'detailPanel.column.packingListCode',
                defaultMessage: '箱单号'
            }),
            dataIndex: 'packingListCode',
            render: (text, record) => ({
                children: text,
                props: {
                    rowSpan: text ? record.rowSpan : 0,
                },
            })
        }, {
            title: formatMessage({
                id: 'detailPanel.column.partSaleOrderCode',
                defaultMessage: '销售订单编号'
            }),
            dataIndex: 'partSaleOrderCode',
            render: (text, record) => ({
                children: text,
                props: {
                    rowSpan: text ? record.rowSpan : 0,
                },
            })
        }, {
            title: formatMessage({
                id: 'detailPanel.column.pickingListCode',
                defaultMessage: '备料单号'
            }),
            dataIndex: 'pickingListCode',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.palletCode',
                defaultMessage: '托盘号'
            }),
            dataIndex: 'palletCode',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.shipmentDate',
                defaultMessage: '出运天数'
            }),
            dataIndex: 'shipmentDate'
        }, {
            title: formatMessage({
                id: 'detailPanel.column.piCode',
                defaultMessage: 'PI编号'
            }),
            dataIndex: 'piCode'
        }, {
            title: formatMessage({
                id: 'detailPanel.column.partCode',
                defaultMessage: '备件编号'
            }),
            dataIndex: 'partCode'
        }, {
            title: formatMessage({
                id: 'newPanel.column.partName',
                defaultMessage: '备件名称'
            }),
            dataIndex: 'partName'
        }, {
            title: formatMessage({
                id: 'detailPanel.column.quantity',
                defaultMessage: '数量'
            }),
            dataIndex: 'quantity'
        }, {
            title: formatMessage({
                id: 'detailPanel.column.price',
                defaultMessage: '单价'
            }),
            dataIndex: 'price',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.totalAmount',
                defaultMessage: '金额'
            }),
            dataIndex: 'totalAmount',
            render: text => formatAmount(text)
        }];
        
        const shipmentColums = [{
            title: formatMessage({
                id: 'detailPanel.column.saleOrderCode',
                defaultMessage: '订单号'
            }),
            dataIndex: 'saleOrderCode'
        }, {
            title: formatMessage({
                id: 'detailPanel.column.partOrderTypeName',
                defaultMessage: '订单类型'
            }),
            dataIndex: 'partOrderTypeName'
        }, {
            title: formatMessage({
                id: 'detailPanel.column.confirmTime',
                defaultMessage: 'PI确认日期'
            }),
            dataIndex: 'confirmTime',
            render: text => formatDateTime(text, DATE_FORMAT)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.creditAuditedTime',
                defaultMessage: '付款日期'
            }),
            dataIndex: 'creditAuditedTime',
            render: text => formatDateTime(text, DATE_FORMAT)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.amount',
                defaultMessage: '出运金额'
            }),
            dataIndex: 'amount',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.amountMeetRate',
                defaultMessage: '累计金额满足率'
            }),
            dataIndex: 'amountMeetRate',
            render: text => formatPercent(text)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.isClose',
                defaultMessage: '是否关闭'
            }),
            dataIndex: 'isClose',
            render: text => text ? formatMessage({
                id: 'detailPanel.column.isCloseYes',
                defaultMessage: 'Yes'
            }) : formatMessage({
                id: 'detailPanel.column.isCloseNo',
                defaultMessage: 'No'
            })
        }];
        return (
            <div>
                <Spin spinning={this.state.isFetching}>
                    <Card>
                        <DescriptionList title={<Row><Col span={6}>{
                            formatMessage({
                                id: 'detailPanel.card.picking',
                                defaultMessage: '订单信息'
                            })
                        }</Col>
                        <Col className={`col-align-right ${styles.detail}`} span={18}>{operations}</Col></Row>}>
                            <Description term={formatMessage({
                                id: 'detail.operation.dealerCode',
                                defaultMessage: '总代编号'
                            })}>{data.dealerCode}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.dealerName',
                                defaultMessage: '总代名称'
                            })}>{data.dealerName}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.country',
                                defaultMessage: '国家/地区'
                            })}>{data.country}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.partContractInvoiceCode',
                                defaultMessage: '发票编号'
                            })}>{data.partContractInvoiceCode}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.currency',
                                defaultMessage: '币种'
                            })}>{conventEnumValueToString(currency, data.currency)}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.invoiceAmount',
                                defaultMessage: '发票金额'
                            })}>{formatAmount(data.invoiceAmount)}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detail.operation.invoicedDate',
                                defaultMessage: '开票日期'
                            })}>{formatDateTime(data.invoicedDate, DATE_FORMAT)}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.shipmentType',
                                defaultMessage: '运输方式'
                            })}>{conventEnumValueToString(transportType, data.shipmentType)}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.origin',
                                defaultMessage: '起运地'
                            })}>{data.origin}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.destination',
                                defaultMessage: '目的地'
                            })}>{data.destination}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.expectDepartedDate',
                                defaultMessage: '预计离港日期'
                            })}>{formatDateTime(data.expectDepartedDate, DATE_FORMAT)}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.declarePlace',
                                defaultMessage: '报关地点'
                            })}>{conventEnumValueToString(declarePlace, data.declarePlace)}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.declareType',
                                defaultMessage: '报关类型'
                            })}>{conventEnumValueToString(declareType, data.declareType)}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.lcCode',
                                defaultMessage: '信用证编号'
                            })}>{data.lcCode}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.isLcl',
                                defaultMessage: 'LCL'
                            })}>{data.isLcl ? formatMessage({
                                    id: 'detailPanel.operation.yesIsLcl',
                                    defaultMessage: '是'
                                }) : formatMessage({
                                    id: 'detailPanel.operation.noIsLcl',
                                    defaultMessage: '否'
                                })}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.shortContainerCount',
                                defaultMessage: '20GP'
                            })}>{data.shortContainerCount}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.standardContainerCount',
                                defaultMessage: '40HQ'
                            })}>{data.standardContainerCount}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.highContainerCount',
                                defaultMessage: '40GP'
                            })}>{data.highContainerCount}
                            </Description>
                        </DescriptionList>
                    </Card>
                    <Card>
                        <DescriptionList title={formatMessage({
                            id: 'detailPanel.table.shipmentDetails',
                            defaultMessage: '满足率清单'
                        })}>
                            <Table
                                className="white-space-nowrap"
                                columns={shipmentColums}
                                rowKey="id"
                                pagination={false}
                                dataSource={shipmentDetails}
                                {...TABLE} />
                        </DescriptionList>
                    </Card>
                    <Card>
                        <DescriptionList title={formatMessage({
                            id: 'detailPanel.table.details',
                            defaultMessage: '清单'
                        })}>
                            <Table
                                className="white-space-nowrap"
                                columns={colums}
                                rowKey="id"
                                pagination={false}
                                dataSource={newDetails}
                                {...TABLE} />
                        </DescriptionList>
                    </Card>
                </Spin>
                <div className="page-toolbar">
                    <Button type="primary" onClick={this.onCancel}>{this.props.intl.formatMessage({
                        id: 'detailPanel.operation.onCancel',
                        defaultMessage: '返回'
                    })}</Button>
                </div>
            </div>
        );
    }
}

DetailPanel.propTypes = {
    history: PropTypes.object,
    id: PropTypes.string,
    intl: PropTypes.object,
    permissions: PropTypes.array
};

import {connect} from 'react-redux';
import {tableSearch} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = (state, props) => ({
    permissions: getPermissions(state)
});

const mapDispatchToProps = (dispatch, props) => ({
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(DetailPanel));
